/*
 * tela.c
 *
 *  Created on: 07/12/2013
 *      Author: vitor
 */

#include "tela.h"

SDL_Surface* screen;

void inicializaTela() {
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
	screen = SDL_SetVideoMode(W_WIDTH, W_HEIGHT, 32,
			SDL_SWSURFACE | SDL_DOUBLEBUF);
	SDL_WM_SetCaption("VM - Tradutores", "VM - Tradutores");
}

void finalizaTela() {
	SDL_Quit();
}

uint8_t pegaValorR(uint8_t valorMemoria) {
	int valorR = valorMemoria >> 5;
	return (uint8_t) (255 * valorR / 7);
}

uint8_t pegaValorG(uint8_t valorMemoria) {
	int valorG = valorMemoria >> 2;
	valorG &= 0x07;
	return (uint8_t) (255 * valorG / 7);
}

uint8_t pegaValorB(uint8_t valorMemoria) {
	int valorB = valorMemoria & 0x03;
	return (uint8_t) (255 * valorB / 3);
}

void plottaMemoriaNaTela(vmInfo* vm) {
	int i;
	int j;
	int enderecoTela;
	SDL_Rect pixel;

	pixel.w = pixel.h = 1;

	for (i = 0; i < W_HEIGHT; i++) {
		pixel.y = i;
		for (j = 0; j < W_WIDTH; j++) {
			pixel.x = j;
			enderecoTela = BASE_TELA + ((i * W_WIDTH) + j);
			SDL_FillRect(screen, &pixel,
					SDL_MapRGB(screen->format,
							pegaValorR(vm->mem[enderecoTela]),
							pegaValorG(vm->mem[enderecoTela]),
							pegaValorB(vm->mem[enderecoTela])));
		}
	}
}

void rotinaTela(vmInfo* vm) {
	while (vm->running && !SDL_QuitRequested()) {
		plottaMemoriaNaTela(vm);
		SDL_Flip(screen);
		SDL_Delay(16);
	}
}
